package com.fish.web.interceptor;

import com.fish.common.constant.JwtConstant;
import com.fish.common.util.JwtUtil;
import com.fish.common.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * JWT拦截器
 * 用于解析JWT Token并设置用户上下文
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头获取Token
        String token = request.getHeader(JwtConstant.TOKEN_HEADER);
        
        if (StringUtils.hasText(token)) {
            // 移除Bearer前缀
            if (token.startsWith(JwtConstant.TOKEN_PREFIX)) {
                token = token.substring(JwtConstant.TOKEN_PREFIX.length());
            }
            
            // 验证Token并解析用户信息
            if (JwtUtil.validateToken(token)) {
                try {
                    Long userId = JwtUtil.getUserId(token);
                    String username = JwtUtil.getUsername(token);
                    
                    // 设置用户上下文
                    UserContext.setUser(userId, username);
                    
                    log.debug("设置用户上下文成功: userId={}, username={}", userId, username);
                } catch (Exception e) {
                    log.warn("解析Token失败: {}", e.getMessage());
                }
            }
        }
        
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 请求处理完成后清除用户上下文
        UserContext.clear();
        log.debug("清除用户上下文");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 确保在异常情况下也能清除用户上下文
        UserContext.clear();
    }
}

